package com.client;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import util.Logger;

import com.client.answers.Answer;
import com.client.answers.CreateRoomAnswer;
import com.client.answers.LoginAnswer;
import com.client.answers.SimpleAnswer;
import com.packages.ClientPackageHandler;
import com.packages.PackageHandler;
import com.sendables.Sendable;

public class CommandSender extends Thread {
	private ClientPackageHandler	cph;
	private OutputStream			os;
	private Monitor					m;
	private int						status	= -1;
	private GUIMonitor				guim;

	public CommandSender(Socket s, Monitor m, ClientPackageHandler cph, GUIMonitor guim)
	{
		this.cph = cph;
		this.m = m;
		this.guim = guim;
		try
		{
			os = s.getOutputStream();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void run()
	{
		while (true)
		{
			byte[] b = null;
			status = m.getStatus(status);
			switch (status)
			{
				case Monitor.SEND_ID_REQ:
					b = cph.prepare(PackageHandler.ID);
					m.setStatus(Monitor.AWAIT_ID_ANS);
					break;
				case Monitor.SEND_ROOM_LIST_REQ:
					b = cph.prepare(ClientPackageHandler.LIST_ROOM_REQ);
					m.setStatus(Monitor.AWAITING_ROOM_LIST_ANS);
					break;
				case Monitor.AWAITING_USER_JOIN_OR_CREATE:
					guim.ask(GUIMonitor.JOIN_OR_CREATE_ACTION);
					SimpleAnswer answer = (SimpleAnswer) guim.getAnswer(GUIMonitor.JOIN_OR_CREATE_ACTION);
					if (answer.getAnswer() == Answer.JOIN)
						m.setStatus(Monitor.AWAITING_USER_ROOM_SELECT);
					else if (answer.getAnswer() == Answer.CREATE) m.setStatus(Monitor.AWAITING_USER_ROOM_CREATE);
					break;
				case Monitor.AWAITING_USER_ROOM_SELECT:
					LoginAnswer la = (LoginAnswer) guim.getAnswer(GUIMonitor.ROOM_JOIN_ACTION);
					b = cph.prepare(ClientPackageHandler.JOIN_ROOM_REQ, Integer.toString(la.getRoomid()),
							la.getPassword());
					m.setStatus(Monitor.AWAITING_JOIN_ROOM_ANS);
					System.out.println("Har skickat iväg login info till server....");
					break;
				case Monitor.AWAITING_USER_ROOM_CREATE:
					CreateRoomAnswer a = (CreateRoomAnswer) guim.getAnswer(GUIMonitor.ROOM_CREATE_ACTION);
					b = cph.prepare(PackageHandler.CREATE_ROOM_REQ, a.getRoomname(), a.getPassword());
					m.setStatus(Monitor.AWAITING_USER_ROOM_CREATE_ANS);
					break;
				case Monitor.AWAITING_DRAWABLE:
					Sendable s = m.getOutgoing();
					b = cph.prepare(ClientPackageHandler.SENDABLE, s);
					break;
			}
			if (b != null)
			{
				try
				{
					os.write(b);
					Logger.getLogger().logg(b);
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	public void postShape(Sendable s)
	{
		m.putOutgoint(s);
	}

}
